package com.industry.system.dal.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.industry.framework.common.redis.RedisUtils;
import com.industry.framework.core.cache.GlobleConstants;
import com.industry.framework.core.cache.CoreSystemCacheBuilder;
import com.industry.system.dal.dataobject.SystemCode;
import com.industry.system.dal.db.SystemCodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author nbZhuozh
 * @Date 2025-04-07  09:58
 **/

@Service
public class SystemCodeCache implements CoreSystemCacheBuilder {
    @Autowired
    private SystemCodeMapper systemCodeMapper;


    @Override
    public void cacheAll()
    {
        List<SystemCode> systemCodes = systemCodeMapper.selectList(Wrappers.lambdaQuery(SystemCode.class));
        if(!CollectionUtils.isEmpty(systemCodes)){
            Map<String, List<SystemCode>> collectTentIdMap =
                    systemCodes.stream().collect(Collectors.groupingBy(SystemCode::getBizType));
            Map<String,String> jksonMap = new HashMap<>();

            collectTentIdMap.forEach((k,v)->{
                String ison = JSON.toJSONString(v, SerializerFeature.WriteDateUseDateFormat);
                //序列化
                jksonMap.put(k,ison);
            });
            RedisUtils.setCacheMap(GlobleConstants.SYSTEM_CODE,jksonMap);
        }
    }


    public List<SystemCode> get(String typeKey){
      return (List<SystemCode>)
              RedisUtils.getCacheMap(GlobleConstants.SYSTEM_CODE)
                      .get(typeKey);
    }

}
